package org.sixtynine.stock.dao.impl;

/**
 * @author Thilan
 *
 */

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.sixtynine.stock.dao.CompanyDao;
import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.Company;
import org.springframework.stereotype.Repository;

@Repository
public class CompanyDaoImpl extends AbstractDaoImpl<Company, Integer> implements
		CompanyDao {

	protected CompanyDaoImpl() {
		super(Company.class);
	}

	@Override
	public void saveCompany(Company company) {
		saveOrUpdate(company);
	}

	@Override
	public List<Company> findCompanyies(String companyName) {
		return findByCriteria(Restrictions.like("name", companyName,
				MatchMode.START));
	}

	@Override
	public List<Company> searchCompany(int sectorId, String code) {
		Criteria criteria = getCurrentSession().createCriteria(Company.class);
		if (sectorId != -1) {
			criteria.add(Restrictions.eq("sector.id", sectorId));
		}
		if (code != null) {
			criteria.add(Restrictions.like("code", code, MatchMode.START));
		}

		// order by ticker
		criteria.addOrder(Order.asc("code"));

		return findByCriteria(criteria);
	}

	@Override
	public Page<Company> searchCompany(int sectorId, String sectorName,
			String companyName, int companyId, GridPramDTO gridPramDTO) {
		Criteria criteria = getCurrentSession().createCriteria(Company.class);
		// order by ticker
		criteria.addOrder(Order.asc("code"));
		if (sectorId != -1) {
			criteria.add(Restrictions.eq("sector.id", sectorId));
		}
		if (sectorName != null) {
			criteria.createAlias("sector", "sec");
			criteria.add(Restrictions.like("sec.name", sectorName,
					MatchMode.START));
		}
		if (companyName != null) {
			criteria.add(Restrictions
					.like("name", companyName, MatchMode.START));
		}
		if (companyId != -1) {
			criteria.add(Restrictions.eq("id", companyId));
		}
		return findByCriteria(criteria, gridPramDTO);
	}

	@Override
	public List<Company> searchCompany(int sectorId) {
		return findByCriteria(Restrictions.eq("sector.id", sectorId));
	}

	@Override
	public Company findCompany(String companyName, int companyId) {
		Criteria criteria = getCurrentSession().createCriteria(Company.class);
		// order by ticker
		criteria.addOrder(Order.asc("code"));

		if (companyName != null) {
			criteria.add(Restrictions.eq("name", companyName));
		}
		if (companyId != -1) {
			criteria.add(Restrictions.eq("id", companyId));
		}
		return findByCriteria(criteria).get(0);
	}

}
